<template>
  <div class="app-container">
    <!-- 告警分析区 -->
    <el-card class="mb16">
      <el-form :inline="true" label-width="90px">
        <el-form-item label="充电站名称">
          <el-select v-model="selectedStationId" placeholder="请选择充电站" @change="fetchAnalysis" style="width: 200px">
            <el-option v-for="item in stationList" :key="item.stationId" :label="item.stationName" :value="item.stationId" />
          </el-select>
        </el-form-item>
      </el-form>
      <el-row :gutter="16" class="mb16">
        <el-col :span="6">
          <el-card>
            <div class="stat-title">告警次数</div>
            <div class="stat-value">{{ analysisData.alarmCount || 0 }} 次</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card>
            <div class="stat-title">告警时长占比</div>
            <div class="stat-value">{{ (analysisData.alarmDurationPercent * 100 || 0).toFixed(2) }}%</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card>
            <div class="stat-title">告警偏好</div>
            <div class="stat-value">{{ analysisData.alarmPreference || '-' }}</div>
          </el-card>
        </el-col>
      </el-row>
      <el-form-item label="月份">
        <el-date-picker
          v-model="selectedMonth"
          type="month"
          value-format="YYYY-MM"
          placeholder="请选择月份"
          @change="fetchAnalysis"
          style="width: 150px"
        />
      </el-form-item>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-card>
            <div class="stat-title">每日告警次数</div>
            <v-chart :option="dailyCountOption" autoresize style="height:300px;" />
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card>
            <div class="stat-title">每日告警时长占比</div>
            <v-chart :option="dailyDurationOption" autoresize style="height:300px;" />
          </el-card>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-card>
            <div class="stat-title">告警类型分布</div>
            <v-chart :option="typeChartOption" autoresize style="height:300px;" />
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card>
            <div class="stat-title">告警等级分布</div>
            <v-chart :option="levelChartOption" autoresize style="height:300px;" />
          </el-card>
        </el-col>
      </el-row>
    </el-card>

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="充电站ID" prop="aStationId">
        <el-input
          v-model="queryParams.aStationId"
          placeholder="请输入充电站ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="充电桩ID" prop="aPileId">
        <el-input
          v-model="queryParams.aPileId"
          placeholder="请输入充电桩ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="充电枪ID" prop="aGunId">
        <el-input
          v-model="queryParams.aGunId"
          placeholder="请输入充电枪ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="告警等级" prop="aLevel">
        <el-input
          v-model="queryParams.aLevel"
          placeholder="请输入告警等级"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="告警时间" prop="aTime">
        <el-date-picker clearable
          v-model="queryParams.aTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择告警时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="持续时长" prop="aDuration">
        <el-input
          v-model="queryParams.aDuration"
          placeholder="请输入持续时长"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:alarm:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:alarm:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:alarm:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:alarm:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="alarmList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="告警主键ID" align="center" prop="aId" />
      <el-table-column label="充电站ID" align="center" prop="aStationId" />
      <el-table-column label="充电桩ID" align="center" prop="aPileId" />
      <el-table-column label="充电枪ID" align="center" prop="aGunId" />
      <el-table-column label="告警类型" align="center" prop="aType" />
      <el-table-column label="告警等级" align="center" prop="aLevel" />
      <el-table-column label="告警时间" align="center" prop="aTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.aTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="持续时长" align="center" prop="aDuration" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:alarm:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:alarm:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改告警信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="alarmRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="充电站ID" prop="aStationId">
          <el-input v-model="form.aStationId" />
        </el-form-item>
        <el-form-item label="充电桩ID" prop="aPileId">
          <el-input v-model="form.aPileId" />
        </el-form-item>
        <el-form-item label="充电枪ID" prop="aGunId">
          <el-input v-model="form.aGunId" />
        </el-form-item>
        <el-form-item label="告警类型" prop="aType">
          <el-input v-model="form.aType" />
        </el-form-item>
        <el-form-item label="告警等级" prop="aLevel">
          <el-input v-model="form.aLevel" />
        </el-form-item>
        <el-form-item label="告警时间" prop="aTime">
          <el-date-picker v-model="form.aTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择告警时间" style="width: 100%" />
        </el-form-item>
        <el-form-item label="持续时长" prop="aDuration">
          <el-input v-model="form.aDuration" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Alarm">
import { ref, reactive, toRefs, onMounted, getCurrentInstance, watch } from 'vue'
import { listAlarm, getAlarm, delAlarm, addAlarm, updateAlarm, getStationList, getAlarmAnalysis, getDailyAlarmCount, getDailyAlarmDurationPercent } from "@/api/system/alarm"
import { use } from "echarts/core"
import VChart from "vue-echarts"
import dayjs from 'dayjs'

import { CanvasRenderer } from "echarts/renderers"
import { PieChart } from "echarts/charts"
import { TitleComponent, TooltipComponent, LegendComponent } from "echarts/components"

use([CanvasRenderer, PieChart, TitleComponent, TooltipComponent, LegendComponent])

const { proxy } = getCurrentInstance()

const alarmList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 分析区相关
const stationList = ref([])
const selectedStationId = ref(null)
const selectedMonth = ref(dayjs().format('YYYY-MM'))
const analysisData = ref({})
const typeChartOption = ref({})
const levelChartOption = ref({})

const dailyCountOption = ref({})
const dailyDurationOption = ref({})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    aStationId: null,
    aPileId: null,
    aGunId: null,
    aType: null,
    aLevel: null,
    aTime: null,
    aDuration: null
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询告警信息列表 */
function getList() {
  loading.value = true
  listAlarm(queryParams.value).then(response => {
    alarmList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    aId: null,
    aStationId: null,
    aPileId: null,
    aGunId: null,
    aType: null,
    aLevel: null,
    aTime: null,
    aDuration: null
  }
  proxy.resetForm("alarmRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.aId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加告警信息"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _aId = row.aId || ids.value
  getAlarm(_aId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改告警信息"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["alarmRef"].validate(valid => {
    if (valid) {
      if (form.value.aId != null) {
        updateAlarm(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addAlarm(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _aIds = row.aId || ids.value
  proxy.$modal.confirm('是否确认删除告警信息编号为"' + _aIds + '"的数据项？').then(function() {
    return delAlarm(_aIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/alarm/export', {
    ...queryParams.value
  }, `alarm_${new Date().getTime()}.xlsx`)
}

// 获取充电站下拉
function fetchStationList() {
  getStationList().then(res => {
    stationList.value = res.data
    if (stationList.value.length > 0) {
      selectedStationId.value = stationList.value[0].stationId
      fetchAnalysis()
    }
  })
}

// 获取分析数据
function fetchAnalysis() {
  if (!selectedStationId.value) return
  getAlarmAnalysis(selectedStationId.value).then(res => {
    analysisData.value = res.data || {}
    // 图表数据处理
    typeChartOption.value = {
      tooltip: { trigger: 'item' },
      legend: { top: 'bottom' },
      series: [{
        name: '类型',
        type: 'pie',
        radius: '60%',
        data: (analysisData.value.typeDistribution || []).map(item => ({
          value: item.count,
          name: item.type
        }))
      }]
    }
    levelChartOption.value = {
      tooltip: { trigger: 'item' },
      legend: { top: 'bottom' },
      series: [{
        name: '等级',
        type: 'pie',
        radius: '60%',
        data: (analysisData.value.levelDistribution || []).map(item => ({
          value: item.count,
          name: item.level
        }))
      }]
    }
  })
  // 新增每日数据请求
  getDailyAlarmCount(selectedStationId.value, selectedMonth.value).then(res => {
    const days = res.data.map(i => i.day)
    const counts = res.data.map(i => i.count)
    dailyCountOption.value = {
      xAxis: { type: 'category', data: days },
      yAxis: { type: 'value' },
      series: [{ data: counts, type: 'bar', name: '告警次数' }],
      tooltip: { trigger: 'axis' }
    }
  })
  getDailyAlarmDurationPercent(selectedStationId.value, selectedMonth.value).then(res => {
    const days = res.data.map(i => i.day)
    const percents = res.data.map(i => (i.percent * 100).toFixed(2))
    dailyDurationOption.value = {
      xAxis: { type: 'category', data: days },
      yAxis: { type: 'value', axisLabel: { formatter: '{value}%' } },
      series: [{ data: percents, type: 'bar', name: '时长占比' }],
      tooltip: { trigger: 'axis' }
    }
  })
}

// 页面加载
onMounted(() => {
  fetchStationList()
})

getList()
</script>

<style scoped>
.stat-title {
  font-size: 16px;
  color: #666;
  margin-bottom: 8px;
}
.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #409EFF;
}
.mb16 {
  margin-bottom: 16px;
}
</style>
